﻿Imports System
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.Design
Imports System.ComponentModel
Imports StartFrame.DA
Imports Common
Imports System.Text


<ToolboxData("<{0}:LNKWebFK runat=""server""> </{0}:LNKWebFK>")> _
Public Class LNKWebFK
    Inherits HiddenField

#Region "Propiedades Publicas"
    Private sLvTabla As String
    <Bindable(True), Category("Data"), DefaultValue("")> Property [LvTabla]() As String
        Get
            Return sLvTabla
        End Get
        Set(ByVal Value As String)
            sLvTabla = Value
        End Set
    End Property

    Private sLvCampo As String
    <Bindable(True), Category("Data"), DefaultValue("")> Property [LvCampo]() As String
        Get
            Return sLvCampo
        End Get
        Set(ByVal Value As String)
            sLvCampo = Value
        End Set
    End Property

    Private sLvDescrip As String
    <Bindable(True), Category("Data"), DefaultValue("")> Property [LvDescrip]() As String
        Get
            Return sLvDescrip
        End Get
        Set(ByVal Value As String)
            sLvDescrip = Value
        End Set
    End Property

    Private sLvWhere As String
    <Bindable(True), Category("Data"), DefaultValue("")> Property [LvWhere]() As String
        Get
            Return sLvWhere
        End Get
        Set(ByVal Value As String)
            sLvWhere = Value
        End Set
    End Property

    Private sTexto As String
    <Bindable(True), Category("Data"), DefaultValue("")> Property [Texto]() As String
        Get
            Return sTexto
        End Get
        Set(ByVal Value As String)
            sTexto = Value
        End Set
    End Property

    Private sObligatorio As Boolean
    <Bindable(True), Category("Behavior"), DefaultValue("")> Property [Obligatorio]() As Boolean
        Get
            Return sObligatorio
        End Get
        Set(ByVal Value As Boolean)
            sObligatorio = Value
        End Set
    End Property

    Private sValida As Boolean
    <Bindable(True), Category("Behavior"), DefaultValue("")> Property [Valida]() As Boolean
        Get
            Return sValida
        End Get
        Set(ByVal Value As Boolean)
            sValida = Value
        End Set
    End Property

    Private sEnabled As Boolean = True
    <Bindable(True), Category("Behavior"), DefaultValue(True)> Property [Enabled]() As Boolean
        Get
            Return sEnabled
        End Get
        Set(ByVal Value As Boolean)
            sEnabled = Value
        End Set
    End Property

#End Region

#Region "Propiedades Privadas"

    Private _datos As String
    Private Property Datos() As String
        Get
            Return _datos
        End Get
        Set(ByVal value As String)
            _datos = value
        End Set
    End Property

    Private _strerror As String
    Private Property StrError() As String
        Get
            Return _strerror
        End Get
        Set(ByVal value As String)
            _strerror = value
        End Set
    End Property

    Private _idreal As String
    Private Property IdReal() As String
        Get
            Return _idreal
        End Get
        Set(ByVal value As String)
            _idreal = value
        End Set
    End Property

#End Region

#Region "Eventos"

#End Region

#Region "Metodos Publicos"
    'Constructor
    Public Sub New()

    End Sub

#End Region

#Region "Metodos Privados y Protegidos"
    Protected Overrides Sub Render(ByVal writer As System.Web.UI.HtmlTextWriter)
        Dim datos As String = ObtenerDatos()
        Dim atributos As String = String.Empty
        Dim txtInput As New TextBox

        If StrError <> String.Empty Then
            MyBase.Render(writer)
            writer.Write("<span style='color:red'>")
            writer.Write(StrError)
            writer.Write("</span>")
        Else
            If Obligatorio Then
                atributos &= " ValidaVacio" & MyBase.ID & "(); "
            End If
            If Valida Then
                atributos &= " ValidaDato" & MyBase.ID & "(); "
            End If

            txtInput.Attributes.Add("onBlur", atributos)
            txtInput.ID = "texto_" & MyBase.ID
            txtInput.Text = Texto
            txtInput.Enabled = Enabled
            txtInput.RenderControl(writer)

            MyBase.Render(writer)


            'Span para ver errores
            writer.Write("<span id='" & MyBase.ID & "Error' style='color:red'>")
            writer.Write(StrError)
            writer.Write("</span>")


            'Parametros para el plugin Automplete de JQuery
            Dim parametros As String
            parametros = "{formatItem: function(item) { return item.des;}}).result(function(event, item) { $('#" & MyBase.ClientID & "').val(item.id);}"

            'Escribimos el codigo JS para aignar al textbox la propiedad autocomplete
            'Page.ClientScript.RegisterStartupScript(Page.GetType, "Script" & Me.ID, _
            '                                            "<script>$('#texto_" & MyBase.ID & "').autocomplete(" & ObtenerDatos() & ", " & parametros & ").flushCache();</script>")
            writer.RenderBeginTag(HtmlTextWriterTag.Script)
            writer.Write("$('#texto_" & MyBase.ID & "').autocomplete(" & ObtenerDatos() & ", " & parametros & ");")
            writer.RenderEndTag()

            If Obligatorio Then
                writer.RenderBeginTag(HtmlTextWriterTag.Script)
                writer.Write(ValidaVacio())
                writer.RenderEndTag()
            End If
            If Valida Then
                writer.RenderBeginTag(HtmlTextWriterTag.Script)
                writer.Write(ValidaDato())
                writer.RenderEndTag()
            End If
        End If
    End Sub

    Private Function ObtenerDatos(Optional ByVal SoloDescrip As Boolean = False) As String
        Dim ds As New DataSet
        Dim datos As String = String.Empty
        Dim sep As String = String.Empty

        Try
            If LvCampo <> String.Empty And LvDescrip <> String.Empty And LvTabla <> String.Empty Then
                ds = Sql.Select(Common.Env.ConnectionString, LvCampo & ", " & LvDescrip, LvTabla, LvWhere)

                If Not SoloDescrip Then
                    datos = "["
                    For Each row As DataRow In ds.Tables(0).Rows
                        datos &= sep & "{id:'" & row(0).ToString & "', des:'" & row(1).ToString & "'}"
                        sep = ","
                    Next
                    datos &= "]"
                Else
                    datos = "["
                    For Each row As DataRow In ds.Tables(0).Rows
                        datos &= sep & "'" & row(1).ToString & "'"
                        sep = ","
                    Next
                    datos &= "]"
                End If
            Else
                StrError = "Ocurrio un error al obtener datos para el campo"
            End If
        Catch ex As Exception
            StrError = "Ocurrio un error al obtener datos para el campo"
            datos = "Array()"
        End Try

        Return datos
    End Function

    Private Function ValidaVacio() As String
        Dim sb As New StringBuilder
        sb.AppendLine("function ValidaVacio" & MyBase.ID & "(){")
        sb.AppendLine(" var control = $('#texto_" & MyBase.ID & "');")
        sb.AppendLine(" var spanError = $('#" & MyBase.ID & "Error');")
        sb.AppendLine(" if(control.val() == ''){ ")
        sb.AppendLine("     spanError.html('Este dato es obligatorio.');")
        sb.AppendLine(" }")
        sb.AppendLine(" else{")
        sb.AppendLine("     spanError.html('');")
        sb.AppendLine(" }")
        sb.AppendLine("}")
        Return sb.ToString
    End Function

    Private Function ValidaDato() As String
        Dim sb As New StringBuilder
        sb.AppendLine("function ValidaDato" & MyBase.ID & "(){")
        sb.AppendLine(" var control = $('#texto_" & MyBase.ID & "');")
        sb.AppendLine(" var spanError = $('#" & MyBase.ID & "Error');")
        sb.AppendLine(" var datos = " & ObtenerDatos(True) & ";")
        sb.AppendLine(" if(control.val() != ''){ ")
        sb.AppendLine("     if(jQuery.inArray(control.val(), datos) == '-1'){")
        sb.AppendLine("         spanError.html('El código ingresado no existe.');")
        sb.AppendLine("     }")
        sb.AppendLine("     else{")
        sb.AppendLine("         spanError.html('');")
        sb.AppendLine("     }")
        sb.AppendLine(" }")
        sb.AppendLine("}")
        sb.AppendLine("")
        Return sb.ToString
    End Function


#End Region

End Class

